﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Data.OracleClient;
using System.Text;

public partial class StudentEntry : BasePage
{
	public const int week1 = 8;
	public const int week2 = 16;
	protected override void pageLoad()
	{
		//SecurityCheck();
		if (!IsPostBack)
		{
			//if (Teacher.IS_ADMIN != 1)
			//{
			//    DataLayer dal = new DataLayer();
			//    string message;
			//    bool result = dal.IsMyStudent(Configuration.ConnectionString, Teacher.TEACHER_ID, StudentId, CurrentInfo.SemesterId, out message);
			//    PALogManager.MessageLog(message);
			//    if (!result)
			//    {
			//        Response.Redirect("error.aspx");
			//    }
			//}


			if (StudentId > 0)
			{
				DataLayer dal = new DataLayer();
				string message;
				Student student = dal.ReadStudent(PAConfiguration.ConnectionString, StudentId, out message);
				PALogManager.MessageLog(message);
				lStudent.NavigateUrl = string.Format("profile.aspx?studentId={0}", StudentId);
				lStudent.Text = student.LASTFIRST;
			}
			checkSection();
			FillGrid();
			go();
		}


	}

	protected void checkSection()
	{
		if (SectionId < 0)
			return;

		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];

		PALogManager.MessageLog(message);

		bool find = false;

		foreach (DataRow dr in data.Rows)
		{
			if ((decimal)dr["SECTION_ID"] == SectionId)
			{
				find = true;
				break;
			}
		}

		if (!find)
		{
			Response.Redirect("error.aspx");
		}
	}

	protected DateTime Date
	{
		get
		{
			if (String.IsNullOrEmpty(Request.QueryString["date"]))
				return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

			return DateTime.Parse(Request.QueryString["date"]);
		}
	}



	protected decimal SectionId
	{
		get
		{
			if (String.IsNullOrEmpty(Request.QueryString["sectionId"]))
				return -1;

			return decimal.Parse(Request.QueryString["sectionId"]);
		}
	}

	protected void FillGrid()
	{
		DataLayer dal = new DataLayer();

		
		DateTime current;
		if (Teacher.IS_ADMIN == 1)
		{
			this.ddlPeriods.DataSource = Manager.GetTwoWeeksForAdmin(Date, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		}
		else
		{
			this.ddlPeriods.Enabled = false;
			this.ddlPeriods.DataSource = Manager.GetTwoWeeks(Date, CurrentInfo.FIRSTDAY, CurrentInfo.LASTDAY, out current);
		}


		try
		{
			if (current != DateTime.MinValue)
				this.ddlPeriods.SelectedValue = current.ToString();
		}
		catch (System.Exception ex)
		{
			PALogManager.ExceptionLog(ex);
		}
		this.ddlPeriods.DataBind();

	}

	public override string Icon
	{
		get
		{
			return "images/attendance_entry_icon.png";
		}
	}
	protected void setCodes()
	{
    DataLayer dal = new DataLayer();
    string message = string.Empty;
    DataTable codes = dal.GetCodes(PAConfiguration.ConnectionString, CurrentInfo.TermId, out message);
    PALogManager.MessageLog(message);
    bool firstChecked = false;
    int i = 0;
    bool flagAdmin = (Teacher.IS_ADMIN == 1);

    foreach (DataRow dr in codes.Rows)
    {
      //if (PAConfiguration.IsSuperUser(Teacher.TEACHER_ID) || dr["ATT_CODE"].ToString() != "O")
      {
        ++i;
        HtmlTableRow tr = CodesRow;
        if (i > 5)
          tr = CodesRow1;

        HtmlTableCell cell = new HtmlTableCell();
        HtmlInputRadioButton checkbox = new HtmlInputRadioButton();

        checkbox.Value = Convert.ToString(dr["ATTENDANCE_CODE_ID"]);
        cell.Controls.Add(checkbox);

        if ((!flagAdmin) && ((dr["ATT_CODE"].ToString() == "E") || (dr["ATT_CODE"].ToString() == "W") ||
          (dr["ATT_CODE"].ToString() == "Q") || (dr["ATT_CODE"].ToString() == "S")))
        {
            //cell.Controls.Remove(checkbox);
            checkbox.Attributes.Add("disabled", "disabled");
        }
        else
        {
            if (!firstChecked)
            {
                checkbox.Checked = true;
                firstChecked = true;
            }
        }

        Label l = new Label();
        l.Font.Size = 9;
        l.Text = String.Format("{0}-{1}", dr["ATT_CODE"], dr["DESCRIPTION"]);

        cell.Controls.Add(l);
        tr.Cells.Add(cell);
      }
    }

    if (flagAdmin)
      ClientScript.RegisterStartupScript(this.GetType(), "isadmin", "var isadmin=1;", true);
    else
      ClientScript.RegisterStartupScript(this.GetType(), "isadmin", "var isadmin=0;", true);
	}

	protected void go()
	{

		if (ddlPeriods.SelectedValue == string.Empty)
			return;


		AttendanceEntry entry = Manager.GetStudentEntry(
			Teacher.TEACHER_ID,
			CurrentInfo.SemesterId,
			StudentId,
			DateTime.Parse(ddlPeriods.SelectedValue),
			DateTime.Parse(ddlPeriods.SelectedValue).AddDays(13));

		Records = entry.Records;

		gvEntries.Columns.Clear();

		HyperLinkField hlf = new HyperLinkField();
		hlf.ItemStyle.Width = 250;
		hlf.DataNavigateUrlFields = new string[] {"STUDENT_ID"};
		hlf.DataNavigateUrlFormatString = "entry.aspx?sectionId={0}";
		hlf.DataTextField = "LastFirst";
		hlf.HeaderText = "Section Name";
		hlf.NavigateUrl = "";
		hlf.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
		hlf.ItemStyle.Font.Size = 10;
		gvEntries.Columns.Add(hlf);
		for (int i = 3; i < 19; i++)
		{
			if (i - 2 == week1)
			{

				TemplateField cf = new TemplateField();
				cf.ItemTemplate = new DynamicButtonTemplate(string.Empty, DataControlRowType.DataRow);
				cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
				
				gvEntries.Columns.Add(cf);

				cf.ItemStyle.Width = 40;

				continue;
			}

			if (i - 2 == week2)
			{

				TemplateField cf = new TemplateField();
				cf.ItemTemplate = new DynamicButtonTemplate(string.Empty, DataControlRowType.DataRow);
				cf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
				gvEntries.Columns.Add(cf);

				cf.ItemStyle.Width = 40;
				continue;
			}

			TemplateField celltemplate = new TemplateField();
			celltemplate.HeaderText = entry.Result.Columns[i].ColumnName;
			celltemplate.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
			celltemplate.ItemTemplate = new DynamicSellTemplate();
			celltemplate.ItemStyle.Width = 40;
			gvEntries.Columns.Add(celltemplate);
		}


	


		setCodes();

		PlaceHolder1.Controls.Add(ParseControl(getHeader(gvEntries.Columns)));

		gvEntries.DataSource = entry.Result;
		gvEntries.DataBind();


	}

	public string getHeader(DataControlFieldCollection dt)
	{
		StringBuilder sb = new StringBuilder();

		sb.Append("<table cellspacing=0 cellpading=0 name='headertable' class='stats2' cellspacing='0' rules='all' border='1' id='headertable' style='border-collapse:collapse;width:100%;' >");
		sb.Append("<tr class='hed2'>");

		foreach (DataControlField dc in dt)
		{
			sb.AppendFormat("<th scope='col'>{0}</th>", dc.HeaderText);
		}

		sb.Append("</tr>");
		sb.Append("</table>");

		return sb.ToString();
	}


	protected void gvEntries_RowDataBound(object sender, GridViewRowEventArgs e)
	{

		if (e.Row.RowType != DataControlRowType.DataRow)
			return;

		DataRow row = ((DataRowView)e.Row.DataItem).Row;

		decimal studentId = (decimal)row["STUDENT_ID"];
		string sectionname =  (string)row["LASTFIRST"];
		decimal enrollmentId = (decimal)row["ENROLLMENT_ID"];

		HtmlInputHidden hiddenField = new HtmlInputHidden();
		hiddenField.Value = string.Format("{0}, {1}", enrollmentId, DateTime.Parse(ddlPeriods.SelectedValue));
		e.Row.Cells[week1].Controls.Add(hiddenField);
		hiddenField = new HtmlInputHidden();
		hiddenField.Value = string.Format("{0}, {1}", enrollmentId, DateTime.Parse(ddlPeriods.SelectedValue).AddDays(7));
		e.Row.Cells[week2].Controls.Add(hiddenField);

		DateTime start = DateTime.Parse(ddlPeriods.SelectedValue);

		HyperLink c = (HyperLink)e.Row.Cells[0].Controls[0];

		if (studentId == decimal.MaxValue)
		{
			c.NavigateUrl = string.Empty;
		}
		bool AllN = true;
		for (int i = 1; i < 8; i++)
		{
			TableCell tc = e.Row.Cells[i];
			DataRow erow = Manager.FindStudentRow(Records, sectionname, start);


			hiddenField = new HtmlInputHidden();
			hiddenField.Value = string.Format("{0}, {1}", enrollmentId, start);
			tc.Controls.Add(hiddenField);
			start = start.AddDays(1);
			Label l = (Label)tc.Controls[0];
			HtmlInputText tb = (HtmlInputText)tc.Controls[1];
			if (erow != null)
			{


				l.Text = (string)erow["ATT_CODE"];
				tb.Value = (string)erow["ATT_CODE"];



				if (erow.IsNull("OTHER_CODES"))
					tb.Attributes["other_codes"] = string.Empty;
				else
				{
					l.ToolTip = string.Format("Other Codes: {0}", (string)erow["OTHER_CODES"]);
					tb.Attributes["other_codes"] = (string)erow["OTHER_CODES"];
				}

				if (tb.Value != "N")
					AllN = false;

			

				if (!erow.IsNull("OTHER_CODES"))
				{
					tc.BackColor = Color.LightBlue;
				}
			}
			else
			{
				AllN = false;
			}

			tc.Controls.Add(l);

		}

		if (AllN)
		{
			e.Row.Cells[0].Attributes["class"] = "bold";
			e.Row.Cells[0].Font.Bold = true;
			for (int i = 1; i < 8; i++)
			{
				TableCell tc = e.Row.Cells[i];
				e.Row.Cells[i].BackColor = Color.Yellow;
			}
		}

		AllN = true;
		for (int i = 9; i < 16; i++)
		{
			TableCell tc = e.Row.Cells[i];

			DataRow erow = Manager.FindStudentRow(Records, sectionname,  start);
			hiddenField = new HtmlInputHidden();
			hiddenField.Value = string.Format("{0}, {1}", enrollmentId, start);
			tc.Controls.Add(hiddenField);

			start = start.AddDays(1);
			Label l = (Label)tc.Controls[0];
			HtmlInputText tb = (HtmlInputText)tc.Controls[1];
			if (erow != null)
			{


				l.Text = (string)erow["ATT_CODE"];
				tb.Value = (string)erow["ATT_CODE"];

				if (tb.Value != "N")
					AllN = false;

				if (erow.IsNull("OTHER_CODES"))
					tb.Attributes["other_codes"] = string.Empty;
				else
				{
					tb.Attributes["other_codes"] = (string)erow["OTHER_CODES"];

					l.ToolTip = string.Format("Other Codes:{0}", (string)erow["OTHER_CODES"]);
				}

				if (!erow.IsNull("OTHER_CODES"))
				{
					tc.BackColor = Color.LightBlue;
				}
			}
			else
			{
				AllN = false;
			}
			tc.Controls.Add(l);
		}

	

		if (AllN)
		{
			e.Row.Cells[0].Attributes["class"] = "bold";
			e.Row.Cells[0].Font.Bold = true;
			for (int i = 9; i < 16; i++)
			{
				TableCell tc = e.Row.Cells[i];


				e.Row.Cells[i].BackColor = Color.Yellow;
			}
		}

	}



	protected DataTable Records
	{
		get
		{
			return (DataTable)Session["Records"];
		}
		set
		{
			Session["Records"] = value;
		}
	}
	protected void lbExport_Click(object sender, EventArgs e)
	{
		DataTable toExcel = Manager.GetStudentEntryForExcel(
					Teacher.TEACHER_ID,
				CurrentInfo.SemesterId,
				StudentId,
				DateTime.Parse(ddlPeriods.SelectedValue),
				DateTime.Parse(ddlPeriods.SelectedValue).AddDays(13));

		Manager.ExportToCSV(toExcel, this.Context, "entry_report.csv");
	}
	protected void bGo_Click(object sender, ImageClickEventArgs e)
	{
		go();
	}
}
